import { insertImg, uploadImage } from './RequestAPI'
import { DismissLoading, ShowLoading } from './ToastUtil'

const UPLOAD_IMG_TYPE = {
  SUCCESS: 'success',
  ERROR: 'error'
}

/**
 * 上传图像单张
 * @param image {
 * imgPath,//图片路径
 * mime//图片类型
 * }
 */
function uploadImg (image, type) {
  return new Promise((resolve) => {
    uploadImage({ params: { uri: image.imgPath, type, mime: image.mime } }).then((data) => {
      resolve({
        type: UPLOAD_IMG_TYPE.SUCCESS,
        data: data.data
      })
    }).catch((err) => {
      resolve({
        type: UPLOAD_IMG_TYPE.ERROR,
        data: err
      })
    })
  })
}

/**
 * 多张图片上传，串行
 * @param localImgs
 * @param type
 * @param showLoading
 * @returns {Promise.<Array>}
 */
export async function uploadImgs ({ localImgs = [], type = 'profile', showLoading = false } = {}) {
  showLoading && ShowLoading()
  const imgArrs = []
  for (const img of localImgs) {
    const item = await uploadImg(img, type)
    if (item.type === UPLOAD_IMG_TYPE.SUCCESS) {
      imgArrs.push(item.data)
    }
  }
  showLoading && DismissLoading()
  return imgArrs
}
